/*
 * user.c
 * 用户程序
 * 
 */

/*头文件*/
//------------------------------------
#include "user.h"
//------------------------------------


/*使用文件，文件指针*/
//------------------------------------
char* user_info="data/user_info.txt";
char* lottery_info="data/lottery_info.txt";
char* lottery_man="data/lottery_man.txt";
char* prize_pool="data/prize_pool.txt";
FILE* f_prize_pool, *f_lottery_man;
//------------------------------------

/*全局变量声明*/
//------------------------------------
int QIHAO, perPrice_lottery, STATE,PRIZE_POOL;
//------------------------------------


/*主函数*/
//------------------------------------
int main(int argc, char **argv)
{
	/*系统清屏*/
	system("clear"); 
	/*欢迎界面*/
	printf("欢迎用户 %s 登陆!\n",argv[1]);
	/*菜单界面*/
	menu(argv[1]);
	/*获取当期信息*/
	int ifempty=1; //查看如果文件没有内容
	f_lottery_man=fopen(lottery_man,"r");
	if(!f_lottery_man){perror("");exit(1);}
	if(fscanf(f_lottery_man,"%d %d %d",\
				&QIHAO,&perPrice_lottery,&STATE)>0)
		ifempty=0; 
	if(ifempty){QIHAO=0,perPrice_lottery=0,STATE=1;}
	fclose(f_lottery_man);
	
	
	User users;   
	xLottery lots;
	
	/*打开用户信息文件定位当前用户信息*/
	FILE* ptemp_user=tmpfile(); //创建临时文件
	if(!ptemp_user){perror("");exit(1);}
	FILE* f_user=fopen(user_info,"r"); //只读打开用户信息
	if(!f_user){perror("");exit(1);}
	while(fscanf(f_user,"%s %s %d",users.name,users.pwd,&users.balance)>0)
	{	
		if(!strcmp(users.name, argv[1]))break; //断开保留文件位置
		fwrite(&users,sizeof(User),1,ptemp_user);
	}
	
	/*定义判断变量*/
	int user_altered=0;
	
	/*选择操作*/
	while(1){
	printf("请输入操作指令：");
	int choose; scanf("%d",&choose);while(getchar()!='\n');
	
	enum sign{_logout, _info_user, _buy, _recharge,_withdraw, _info_lotteries, _pwdAlter, _cancel,  _menu=11, _sysout=99};
	enum {isDele,notDele};
	
	switch(choose){
		case _logout: 
		if(user_altered)save_user(&users, f_user, ptemp_user,notDele); 
		exit(0);
		break;
		case _sysout: 
		if(user_altered)save_user(&users, f_user, ptemp_user,notDele); 
		exit(3);
		break;
		case _info_user: info_user(&users);
		break;
		case _buy: ++user_altered;buy(&users);
		break;
		case _recharge: ++user_altered;recharge(&users);
		break;
		case _withdraw: ++user_altered;withdraw(&users);
		break;
		case _info_lotteries: info_lotteries(&users, &lots);
		break;
		case _pwdAlter: ++user_altered; pwdAlter(&users);
		break;
		case _cancel: 
		printf("确定注销吗?(按'y'确定，任意键取消)："); 
		char c; scanf("%c",&c);while(getchar()!='\n');
		if(c=='y'){
			cancel_lots(&users,&lots);
			save_user(&users, f_user, ptemp_user,isDele); 
			exit(0);
		}
		break;
		case _menu: menu(argv[1]);
		break;
		
		default: printf("input error!\n");break;
		}
	}
	return 0;
}
